<template>
  <div class="difficulty-table" id="handlePrint">
    <h2>{{ title }}</h2>
    <el-table :data="tableData" border>
      <el-table-column prop="id" label="序号" />
      <el-table-column prop="userName" label="姓名" />
      <el-table-column prop="sex" label="性别" />
      <el-table-column :label="'组别'" width="120">
        <template #default="{ row }">
          {{ getGroupName(row.matchesGroupId) }}
        </template>
      </el-table-column>
      <el-table-column :label="'单位'" width="200">
        <template #default="{ row }">
          {{ getTeamName(row.teamGroupId) }}
        </template>
      </el-table-column>
      <el-table-column :label="'项目'" width="120">
        <template #default="{ row }">
          {{ getProjectName(row.projectId) }}
        </template>
      </el-table-column>
      <el-table-column v-for="(label, index) in actionLabels" :key="index" :label="label">
        <template #default="{ row }">
          {{ row.userCodes[index]?.code || '' }}({{ row.userCodes[index]?.score || '' }})
        </template>
      </el-table-column>
      <el-table-column prop="totalScore" label="难度总分" />
    </el-table>
    <!-- 打印按钮 -->
    <el-select v-model="projectId" placeholder="请选择项目" @change="handleProjectChange">
      <el-option v-for="project in matchprojectid" :key="project.id" :label="project.projectName"
        :value="project.id"></el-option>
    </el-select>
    <el-button type="primary" v-print="printConfig" class="print-button-container">打印</el-button>
    <el-button type="primary" @click="handleCancel" class="print-button-container">取消</el-button>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import axios from 'axios';

const actionLabels = ref('');

const title = ref();

const route = useRoute();
const router = useRouter();

const token = localStorage.getItem('adminToken');
const matchid = route.query.matchid;

const projectId = ref('');
const matchprojectid = ref([]);
const matchgroupid = ref([]);
const teamstaff = ref([]);

const groupMap = ref({});
const teamMap = ref({});
const projectMap = ref({});
const tableData = ref([]);

const numbers = ref();

// 获取当前比赛信息
async function fetchmatch() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/match/${matchid}`, {
      headers: {
        'Authorization': `Bearer  ${token}`
      }
    })
    const matchname = response.data.match;
    matchname.map(match => {
      title.value = match.title;
    });
  } catch (error) {
    console.log(error)
  }
}

fetchmatch();



// 辅助函数：解析并计算分数
function parseAndSumScores(scoreStr) {
  if (!scoreStr) return 0;
  const scores = scoreStr.split('+').map(Number);
  return scores.reduce((sum, score) => sum + (isNaN(score) ? 0 : score), 0);
}

// 预处理数据，添加动作1到18的属性
function preprocessData(data) {
  return data.map(athlete => {

    // 确保每个athlete都有userCodes和scores数组
    const scores = athlete.userCodes;


    const fen = scores.map((scoreObj, idx) => {
      if (scoreObj && scoreObj.score) {
        const scoreid = parseAndSumScores(scoreObj.score);
        return scoreid;
      }
      return
    });

    const zongfen = fen.reduce((sum, current) => sum + current, 0); // 计算总分
    const actionScores = actionLabels.value.map((_, index) => {
      const scoreObj = scores.map(score => ({ code: score.code, score: score.score }));
      return {
        code: scoreObj[index]?.code || '-',
        score: scoreObj[index]?.score || '-'
      };
    });

    return {
      ...athlete,
      userCodes: actionScores,
      totalScore: zongfen.toFixed(3)
    };
  });
}

// 获取渲染页面的数据
async function handleProjectChange(projectIdValue) {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/api/getProjectDifficultyDeclare/${projectIdValue}`, {
      headers: { 'Authorization': 'Bearer ' + token },
    });

    if (response.data && response.data.data) {
      const count = response.data.data;
      console.log(count);

      // 假设每个对象中都有一个 userCodes 属性，它是一个数组
      numbers.value = count.map(item => {
        // 检查 userCodes 是否为数组
        if(item){
          const userCodes = item.userCodes;
          // 如果 userCodes 是数组，返回其长度
          return userCodes.length;
        }
        // 如果 userCodes 不是数组，返回 0 或其他默认值
        return 0;
      });

      // 找到所有 userCodes 长度中的最大值
      const maxLengthOfAll = Math.max(...numbers.value);
      numbers.value = maxLengthOfAll; // 将最大值赋值给 numbers
      // 定义动作标签
      actionLabels.value = Array.from({ length: numbers.value }, (_, i) => `编码与分值${i + 1}`);
      tableData.value = preprocessData(response.data.data);
    } else {
      console.error('Invalid response data:', response.data);
      tableData.value = [];
    }

  } catch (error) {
    console.error('Error fetching project data:', error);
    tableData.value = [];
  }
}

// 获取matchid对应的队伍
async function getMatchTeams() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/teamstaff/getTeamByStaff/${matchid}`, {
      headers: { 'Authorization': 'Bearer ' + token },
    });
    teamstaff.value = response.data.teamStaffs || [];
  } catch (error) {
    console.error('Error fetching team data:', error);
    teamstaff.value = [];
  }
}

// 获取matchid对应项目
async function matchproject() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/project/${matchid}`, {
      headers: { 'Authorization': 'Bearer ' + token },
    });
    matchprojectid.value = response.data.project || [];
  } catch (error) {
    console.error('Error fetching project data:', error);
    matchprojectid.value = [];
  }
}

// 获取matchid对应组别
async function matchgroup() {
  try {
    const response = await axios.get(`http://back1.idcfengye.com:15173/competition/matchgroup/${matchid}`, {
      headers: { 'Authorization': 'Bearer ' + token },
    });
    matchgroupid.value = response.data.matchgroup || [];
  } catch (error) {
    console.error('Error fetching match group data:', error);
    matchgroupid.value = [];
  }
}

function populateMaps() {
  matchgroupid.value.forEach(group => {
    groupMap.value[group.id] = group.groupname || '-';
  });
  teamstaff.value.forEach(team => {
    teamMap.value[team.id] = team.teamName || '-';
  });
  matchprojectid.value.forEach(project => {
    projectMap.value[project.id] = project.projectName || '-';
  });
}

async function initializeData() {
  await getMatchTeams();
  await matchgroup();
  await matchproject();
  populateMaps();
}

function getGroupName(groupId) {
  return groupMap.value[groupId] || '-';
}

function getTeamName(teamId) {
  return teamMap.value[teamId] || '-';
}

function getProjectName(projectId) {
  return projectMap.value[projectId] || '-';
}

const printConfig = {
  id: 'handlePrint',
  extraCss: ['https://cdn.example.com/print-style1.css', 'https://cdn.example.com/print-style2.css'],
};

function handleCancel() {
  router.push({ path: '/admin/viewproject', query: { id: matchid } });
}

onMounted(() => {
  initializeData();
});
</script>

<style scoped>
.difficulty-table {
  text-align: center;
}

.print-button-container {
  width: 100px;
  margin-left: 48%;
  margin-top: 10px;
}

@media print {
  .difficulty-table {
    width: 100%;
  }

  .el-table {
    width: 100% !important;
  }

  .el-table__body-wrapper {
    overflow: visible !important;
  }

  /* 其他打印时的样式调整 */
}
</style>